package com.service.impl;

import com.dao.MessageDao;
import com.entity.Message;
import com.entity.Result;
import com.entity.User;
import com.service.MessageServer;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class MessageServerImpl implements MessageServer {

    @Autowired
    MessageDao messageDao;

    //得到消息
    @Override
    public Result getInfos(String date, HttpServletRequest request) {
//        System.out.println(date);

//                通过session得到用户信息
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute("user");
        Integer uNo=user.getuNo();

//        Integer uNo=0;

        if(date!=null){
            //正则表达式验证date是否满足格式yyyy-MM-dd
            String regex = "((19|20)[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])";
            Pattern pattern=Pattern.compile(regex);
            Matcher matcher=pattern.matcher(date);
            if(!matcher.matches()){
                //不匹配
                date=null;
            }
        }

        //查询消息
        List<Message> infos=messageDao.queryInfos(date,uNo);
        System.out.println(infos);
        Result result=new Result(true,"ok",infos);
        return result;
    }

    //确认消息
    @Override
    public void confirmInfo(Integer mid) {
        messageDao.updateInfoStatus(mid);
    }

    //得到消息个数
    @Override
    public Result getInfoNum(HttpServletRequest request) {
//1

        //        通过session得到用户信息
        HttpSession session= request.getSession(false);

        User user=(User) session.getAttribute("user");
        Integer uNo=user.getuNo();


//        Integer uNo=0;
        //查询消息
        List<Message> infos=messageDao.queryInfos(null,uNo);
        int infonum=infos.size();
        Result result=new Result(true,"ok",infonum);

        return result;
    }

    //发送消息给管理员
    @Override
    public void sendText(String title,String sendText ,HttpServletRequest request) {

        //        通过session得到用户信息
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute("user");
        Integer uNo=user.getuNo();

//        Integer uNo=1;

        Date nowTime=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String date=sdf.format(nowTime);
        messageDao.addInfo(uNo,title,sendText,date);
    }
}
